package chatstuff;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Utterance {

	String teamId;

	String id;
	String refId;

	int idNo;
	int refIdNo;

	String nickname;
	String content;

	String tag;

	public Utterance(String teamId, String id, String refId, String nickname,
			String content, String tag) {
		super();

		this.teamId = teamId;
		this.id = id;
		this.refId = refId;
		this.nickname = nickname;
		this.content = content;
		this.tag = tag;

	}

	public Utterance(String teamId, String id, String refId, String nickname,
			String content) {
		this(teamId, id, refId, nickname, content, "-");
	}

	public String toString() {
		return teamId + "\t" + id + "\t" + refId + "\t" + nickname + "\t"
				+ content + "\t" + tag;
	}

	public static Utterance parseUtterance(String utteranceString)
			throws Exception {

		String u[] = utteranceString.split(",");
		if (u.length < 5 || u.length > 6) {
			throw new Exception("Utterance parse exception");
		}
		if (u.length == 5)
			return new Utterance(u[0], u[1], u[2], u[3], u[4]);
		else
			return new Utterance(u[0], u[1], u[2], u[3], u[4], u[5]);
	}

	public static void writeToFile(ArrayList<Utterance> utterances,
			String filePath) {
		try {
			FileWriter outFile = new FileWriter(filePath);
			PrintWriter out = new PrintWriter(outFile);
			for (Utterance u : utterances) {
				out.println(u.toString());
			}
			out.close();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	public static ArrayList<Utterance> readFromFile(String filePath) {
		ArrayList<Utterance> utterances = new ArrayList<Utterance>();
		try {
			BufferedReader br = new BufferedReader(new FileReader(new File(
					filePath)));

			String line;
			while ((line = br.readLine()) != null) {
				Utterance u = Utterance.parseUtterance(line);
				utterances.add(u);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return utterances;
	}
}
